package com.shadow.study.test.线程;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@EnableAsync
@Configuration
public class AsyncConfig {

    /* 核心线程数 */
    private static final String THREAD_NAME_PREFIX = "d-";
    /* 核心线程数 */
    private static final int CORE_POOL_SIZE = 2;
    /* 最大线程数 */
    private static final int MAX_POOL_SIZE = 3;
    /* 缓冲队列 */
    private static final int QUEUE_CAPACITY = 5;
    /* 空闲时间 */
    private static final int KEEP_ALIVE_SECONDS = 60;

    @Bean("dThreadPool")
    public Executor dThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        executor.initialize();
        return executor;
    }

    @Bean
    public ThreadPoolManagement dThreadPoolManagement() {
        return new ThreadPoolManagement();
    }

    public class ThreadPoolManagement {

        public int getQueueSize() {
            ThreadPoolExecutor executor = ((ThreadPoolTaskExecutor) dThreadPool()).getThreadPoolExecutor();
            return executor.getQueue().size();
        }

        public int getActiveCount() {
            ThreadPoolExecutor executor = ((ThreadPoolTaskExecutor) dThreadPool()).getThreadPoolExecutor();
            return executor.getActiveCount();
        }
    }
}
